package com.share.hello.service;

import com.share.hello.mapper.UserMapper;
import com.share.hello.model.User;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author caifan
 * @created 2021/12/17
 * @description:
 */
@Service
public class UserService {

    private final String REGION = "region";

    @Autowired
    private CacheChannel cacheChannel;

    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        CacheObject cacheObject = cacheChannel.get(REGION, "user" + id);
        Object value = cacheObject.getValue();
        if (Objects.nonNull(value)) {
            System.out.println("from cache");
            return (User)value;
        }
        User user = userMapper.selectById(id);
        if (Objects.nonNull(user)) {
            System.out.println("from db and set cache");
            cacheChannel.set("region", "user" + id, user);
        }
        return user;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean addUser(User user) {
        int insert = userMapper.insert(user);
        return insert > 0;
    }

}
